package org.txazo.blog.web.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.txazo.blog.commons.scan.ActionUriScanner;
import org.txazo.blog.commons.scan.StaticResourceUriScanner;
import org.txazo.blog.commons.xml.XmlLoader;
import org.txazo.blog.util.HttpUtil;
import org.txazo.blog.util.StringUtil;

/**
 * CoreFilter - 核心过滤器
 * 
 * @author Tu XiaoZhou
 * @since 2013-08-10
 * 
 */
public class CoreFilter implements Filter {

	/** 首页跳转URL */
	private static String index = null;
	/** 登录页跳转URL */
	private static String login = null;
	/** 允许地址栏访问URI */
	private static Set<String> uris = new HashSet<String>();
	/** 动态资源URI */
	private static Set<String> actionUris = new HashSet<String>();
	/** 静态资源URI */
	private static Set<String> staticResourceUris = new HashSet<String>();

	static {
		index = HttpUtil.getFullRedirectURL("/index.jsps");
		login = HttpUtil.getFullRedirectURL("/login/index.jsps");

		try {
			uris = XmlLoader.loaderUri();
		} catch (Exception e) {
			e.printStackTrace();
		}

		actionUris = new ActionUriScanner().scan();
		staticResourceUris = new StaticResourceUriScanner().scan();
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		String uri = request.getRequestURI();
		String refer = request.getHeader("Referer");

		if (uri.equals("/")) {
			/** uri: / */
			response.sendRedirect(index);
		} else if (HttpUtil.isDynamicRequestOfURI(uri)
				&& actionUris.contains(uri)) {
			if (StringUtil.isEmpty(refer) && !uris.contains(uri)) {
				/** uri: /namespace/action.jsps */
				response.sendRedirect(login);
			} else {
				/** uri: /namespace/action.jsps */
				chain.doFilter(req, resp);
			}
		} else if (HttpUtil.isStaticResourceOfURI(uri)
				&& staticResourceUris.contains(uri)) {
			if (StringUtil.isEmpty(refer)) {
				/** 静态资源拒绝地址栏访问 */
				response.sendRedirect(HttpUtil
						.getFullRedirectURL("/common/status403.jsps"));
			} else {
				/** 页面静态资源 */
				chain.doFilter(req, resp);
			}
		} else if (uri.equals("/favicon.ico")) {
			/** uri: /favicon.ico */
			chain.doFilter(req, resp);
		} else {
			/** 非法URI */
			response.sendRedirect(HttpUtil
					.getFullRedirectURL("/common/status404.jsps"));
		}
	}

	@Override
	public void destroy() {
	}

}
